//
//  HeaderSearchBar.swift
//  suda
//
//  Created by youai on 2019/7/23.
//  Copyright © 2019年 youi. All rights reserved.
//

import Foundation
import UIKit
import RxSwift
import RxCocoa

//页面上部的搜索栏
class HeaderSearchBar : UIView, UITextFieldDelegate {
    let textfield = TextField()
    func setParent(vc:BaseViewControllerWithHeader) {
        vc.safeView.addSubview(self)
        self.snp.makeConstraints { (make) in
            make.left.right.equalToSuperview()
            make.top.equalTo(vc.headView.snp.bottom)
            make.height.equalTo(49)
        }
        self.drawImage(named: "magnifying_glass") { (make) in
            make.left.equalToSuperview().offset(13)
            make.centerY.equalToSuperview()
        }
        let background = self.drawImage(named: "header_search_bk") { (make) in
            make.left.equalToSuperview().offset(42)
            make.centerY.equalToSuperview()
        }
        self.drawTextField(textField: textfield, placeholder: "编号或名称等关键字", fontSize: 11,   returnKeyType: .search) { (make) in
            make.left.equalTo(background).offset(16)
            make.right.equalTo(background).offset(-16)
            make.centerY.equalToSuperview()
        }
        textfield.clearButtonMode = .whileEditing
        textfield.hitEdgInsets = .init(top: -10, left: -20, bottom: -10, right: -20)
        textfield.horizontalFittingSize()
        textfield.inputAccessoryView = BaseViewController.createAccessoryToolBar(target: self, action: #selector(textFieldPressReturn))
        textfield.delegate = self
        _ = textFieldReturn.takeUntil(self.rx.deallocated)
    }
    
    let textFieldReturn = PublishSubject<()>()
    @objc func textFieldPressReturn(){
        _ = textFieldShouldReturn(self.textfield)
    }
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        textField.endEditing(true)
        textFieldReturn.onNext(())
        return true
    }
    
    override var isUserInteractionEnabled: Bool{
        get { return super.isUserInteractionEnabled}
        set{
            super.isUserInteractionEnabled = newValue
            if !self.isUserInteractionEnabled {
                if textfield.isFirstResponder {
                    textfield.resignFirstResponder()
                }
            }
        }
    }
}
